package com.example.tests;

import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.MovieEditPage;
import com.example.pages.MovieListPage;
import com.example.pages.MoviePage;

import ru.esteru.selenium.factory.WebDriverFactory;

public class ChangeMovieDescriptionTest {
  private WebDriverWait wait;
  private WebDriver driver;
  private String baseUrl;
  private StringBuffer verificationErrors = new StringBuffer();
  private LoginPage loginPage;
  private MovieListPage movieListPage;
  private MoviePage moviePage;
  private MovieEditPage movieEditPage;
  private InternalPage somePage;

  @Before
  public void setUp() throws Exception {
    driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
    baseUrl = "http://localhost/";
    wait = new WebDriverWait(driver, 10);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void changeMovieDescriptionTest() throws Exception {
	openHomePage();
    loginAs("admin", "admin");
    openMovieDescPage();
    changeMovieDesctioption("Very mad movie");
    assertTrue(driver.findElements(By.linkText("Edit")).size() >0);
    logOut();
  }

private void logOut() {
	somePage.menuLogoutLink.click();
	wait.until(alertIsPresent()).accept();
}

private void changeMovieDesctioption(String notes) {
	movieEditPage.notesField.clear();
	movieEditPage.notesField.sendKeys(notes);
	movieEditPage.submitButton.click();
}

private void openMovieDescPage() {
	movieListPage.movieBoxField.click();
    moviePage.EditLink.click();
}

private void loginAs(String username, String password) {
	loginPage.userNameField.clear();
    loginPage.userNameField.sendKeys(username);
    loginPage.passwordField.clear();
    loginPage.passwordField.sendKeys(password);
    loginPage.loginButton.click();
}

private void openHomePage() {
	driver.get(baseUrl + "php4dvd/");
	loginPage = PageFactory.initElements(driver, LoginPage.class);
	movieListPage = PageFactory.initElements(driver, MovieListPage.class);
	moviePage = PageFactory.initElements(driver, MoviePage.class);
	movieEditPage = PageFactory.initElements(driver, MovieEditPage.class);
	somePage = PageFactory.initElements(driver, InternalPage.class);
	
}

  @After
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }
}